package com.class06.dao.impl;

import com.class06.dao.StudentDao;
import com.class06.pojo.Student;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class StudentDaoImpl implements StudentDao {
    private JdbcTemplate jdbcTemplate;

    //    提供set方法，用于注入jdbcTemplate对象
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public List<Student> queryAllStudent() {
//        1、创建sql语句  如果java实体类和数据库表名不一致，需要使用as关键字进行映射
        String sql = "select id,name,gender,age,class as classes from students";

        List<Student> studentList = jdbcTemplate.
//                new BeanPropertyRowMapper<>(Student.class)   将结果集封装到Student对象中
        query(sql, new BeanPropertyRowMapper<>(Student.class));
        return studentList;
    }

    @Override
    public int addStudent(Student student) {

//        1、创建sql语句  ? 占位符
        String sql = "insert into students values(?,?,?,?,?)";
//        2、调用update方法进行增加操作
        int update = jdbcTemplate.update(sql,
                student.getId(), student.getName(), student.getGender(),
                student.getAge(), student.getClasses());
        return update;
    }

    @Override
    public int deleteStudent(Integer id) {

        String sql = "delete from students where id=?";
        int update = jdbcTemplate.update(sql, id);
        return update;
    }

    @Override
    public int updateStudent(Student student) {
        String sql = "update students set name=? ," +
                "gender=?,age=?,class=? where id=?";
        int update =  jdbcTemplate.update(sql,student.getName(),student.getGender(),
                student.getAge(),student.getClasses(),student.getId());
        return update;
    }
}
